package com.wlstock.funi.utils;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.RemoteViews;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.dialog.PopTradeDialog;
import com.wlstock.funi.model.AIAccountsModel;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundModel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


public class NotiUtils {

	private static final String ISRECORD = "isrecord";
	private static final String SPEAK = "speak";
	private static final String DIS_ID = "disId";
	private static final String CONTENT = "content";
	private static final String TITLE = "title";

	@SuppressLint("NewApi")
	public static void showSimpleNoti(Context context,int id ,String title, String content, int icon) {
		if (icon == 0) {
			icon = R.drawable.ic_launcher;
		}
		Notification noti = new Notification(icon, null, System.currentTimeMillis());
		RemoteViews remView = new RemoteViews(context.getPackageName(), R.layout.layout_noti_simple);
		remView.setTextViewText(R.id.tv_noti_title, title);
		remView.setTextViewText(R.id.tv_noti_content, content+ "更新时间:"+TimeUtils.getCurrentHHMM());
		noti.contentView = remView;
//		noti.defaults = Notification.DEFAULT_ALL;
		String uri = "android.resource://" + context.getPackageName() + "/" + R.raw.ma5;
		Uri no = Uri.parse(uri);
		noti.sound = no;
		noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
		noti.priority = 10000;
		NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notiManager.notify(id, noti);
	}

	@SuppressLint("NewApi")
	public static void showOperateModeNoti(Context context, OperateModel operateModel) {
//		int tradeRange = OperateDao.getInstance(context).getFundNameRange(operateModel.getFundid(),operateModel.getSeason());//排名
//		int size = OperateDao.getInstance(context).getOperList(operateModel.getFundid(),operateModel.getSeason()).size();//交易人数
//		float nums = CaculateUtils.getTradeMoney(operateModel.range, operateModel.nums)/operateModel.getTradePrice();
		
		String notiTitle = operateModel.getFundName()+"在"+operateModel.getTradedDay()+" "+operateModel.getTradedHourMinute()+"以  "+operateModel.getTradePrice();
		String opTypeWithStkCode = operateModel.getRemark()+operateModel.getStockName();
		String notiContent =opTypeWithStkCode + "(" + operateModel.getStockNo() + ")" + "创建时间:" + TimeUtils.parseHHMM(operateModel.getCreatedTime());
		String notiAnalize = "本期: "+CaculateUtils.getPercentByFloat(operateModel.getProfitRate()) +" 总收益:"+CaculateUtils.getPercentByFloat(operateModel.getTotalIncome())+" 排名:"+operateModel.range;

		RemoteViews notiViews = new RemoteViews(context.getPackageName(), R.layout.layout_noti_customview);
		notiViews.setTextViewText(R.id.tv_noti_title, notiTitle);
		notiViews.setTextViewText(R.id.tv_noti_content, notiContent);
		notiViews.setTextViewText(R.id.tv_noti_analise, notiAnalize);
		float offset = -1.0f;
		if (operateModel.getTradeType() == OperateModel.TradeType_BUY) {
			offset = TradeSetUtils.getBuyOffset(context, operateModel.getFundid());	
		} else {
			offset = TradeSetUtils.getSaleOffset(context, operateModel.getFundid());
		}
		notiViews.setTextViewText(R.id.tv_noti_confidence, CaculateUtils.getTradeTips(operateModel.getRemark(), operateModel.getTradePrice(),offset));
		notiViews.setTextViewText(R.id.tv_noti_stock_counts,CaculateUtils.getTradePty(context, operateModel.getFundid(), operateModel.getTradePrice(), operateModel.nums) + "股");
		
		Notification noti = new Notification(R.drawable.ic_operator, null, System.currentTimeMillis());
		noti.defaults = Notification.DEFAULT_ALL;
		noti.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
		
		Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.hexin.plat.android");
		if (intent!=null) {
			PendingIntent pIntent = PendingIntent.getActivity(context, IntentContants.REQUEST_START_STARTACTIVITY, intent, 0);
			noti.contentIntent = pIntent;
		}
		noti.contentView = notiViews;
		NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notiManager.notify(NotiIdGenerator.generate(operateModel.getStockNo(), NotiIdGenerator.GenerFrom.WLTRADER), noti);
		
		FundApplication.getInstance().speak(notiTitle+opTypeWithStkCode);
	}
	
	/*提示fundmo的*/
	public static void showSelfFundMode(Context context,SelfFundModel selfFundModel) {
		// TODO Auto-generated method stub
		Notification noti = new Notification(R.drawable.ic_self_fund, null, System.currentTimeMillis());
		HashMap<String, String> hash = fundModeNotis(selfFundModel);
		String content = hash.get(CONTENT);
		String title = hash.get(TITLE);
		String isRecord = hash.get(ISRECORD);
		String speak = hash.get(SPEAK);
		
		if (!StrUtils.isNullOrEmpty(title) && !StrUtils.isNullOrEmpty(content) ) {
			RemoteViews remView = new RemoteViews(context.getPackageName(), R.layout.layout_noti_simple);
			remView.setTextViewText(R.id.tv_noti_title, title);
			remView.setTextViewText(R.id.tv_noti_content, content);
			noti.contentView = remView;
			noti.defaults = Notification.DEFAULT_ALL;
			noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
			NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
			notiManager.notify(NotiIdGenerator.generate(selfFundModel.getStockNo(), NotiIdGenerator.GenerFrom.SELFFUND), noti);
		}
		
		if (selfFundModel.isRecord!=null) {
			if ("Y".equals(selfFundModel.isRecord)) {
				FundApplication.getInstance().speak(speak);
			}
		}else{
			if ("Y".equals(isRecord)) {
				FundApplication.getInstance().speak(speak);
			}	
		}
		
	}
	
	public static HashMap<String, String> fundModeNotis(SelfFundModel model){
		HashMap<String, String> hash = new HashMap<String, String>();
		StringBuffer titleSB   = new StringBuffer();
		StringBuffer contentSB = new StringBuffer();
		StringBuffer disBuffer = new StringBuffer();
		StringBuffer speakSB   = new StringBuffer();
		String       isRecord  = "Y";   
		if (model.getSourceCode() == SelfFundModel.SOURCE_WANGLONG) {

			String tradeType = "";
			if (model.getTradeType() == OperateModel.TradeType_BUY) {
				tradeType = "买入";
			} else if (model.getTradeType() == OperateModel.TradeType_SELL) {
				tradeType = "卖出";
			}

			float dis = CaculateUtils.getCurPriceDis2TrPrice(model);
			String disStr = StockUtils.priceOffsetType(dis);
			String disStrValue = CaculateUtils.getPercentByFloat(dis);

			//xxx跌至长波1号今天买入价格的5% 高位回落
			titleSB.append(model.getStockName()).append(disStr).append(model.getFundName()).append(model.getTradedDay()).append(tradeType).append("价格的").append(disStrValue);
			//第x的长波1号昨天买入的xxx跌至5% 高位回落
			speakSB.append("第").append((int)model.getRange()).append("名").append(model.getTradedDay()).append(tradeType).append(model.getStockName()).append(disStr).append(disStrValue).append(model.cur2highAbsDisStr());
			
			contentSB.append(model.nameWithCode()).append(model.curPrice()).append(model.cur2CloseDisAbsDisStr());
			contentSB.append("\n").append("本期:").append(CaculateUtils.getPercentByFloat(model.getProfitRate())).append("  排名:")
					.append(model.getRange()).append("  持仓:").append(model.getNums()).append("人 ").append(model.cur2highAbsDisStr());
			
			int precentDis = Math.abs((int) dis);
			
			//可以通过这个 precentDis 来控制多少的比率进行播报,只播报浮动盈亏少于10%的
			if (precentDis/2 == 0 && dis < 8) {
				isRecord = "Y";
			}else {
				isRecord = "N";
			}
			disBuffer.append(precentDis);
			
		}else if (model.getSourceCode() == SelfFundModel.SOURCE_ZB) {
			float curDis2LastClose = CaculateUtils.getFloatDis(model.getCurPrice(), model.getlastClose());
			float curDis2Highest = CaculateUtils.getFloatDis(model.getCurPrice(), model.gethPrice());
			//上证指数上涨0.5%
			speakSB.append(model.getStockName()).append(StockUtils.priceOffsetType(curDis2LastClose)).append(CaculateUtils.getPercentByFloat(curDis2LastClose)).append("报").append(model.getCurPrice());
			isRecord = "Y";
		}
		
		hash.put(TITLE,   titleSB.toString());
		hash.put(CONTENT, contentSB.toString());
		hash.put(DIS_ID,  disBuffer.toString());
		hash.put(SPEAK,   speakSB.toString());
		hash.put(ISRECORD,isRecord);
		
		return hash;
	}

	public static void showMyAccountMode(Context context, MyAccountStocks ownStock, SelfFundModel sfModel){
		String owner = "默认";
		if (ownStock.getClass().equals(MyAccountStocks.class)) {
			owner = "真实帐号";
		}else if (ownStock.getClass().equals(AIAccountsModel.class)) {
			owner = "模拟帐号";
		}

		String profitType = "";
		if (ownStock.getProfitRate() > 0) {
			profitType = "上涨";
		}else {
			profitType = "下跌";
		}
		//持有XXX上涨5% 今日: 涨跌3%
		StringBuffer sbTitle = new StringBuffer("");
		sbTitle.append(owner).append("持有"+ownStock.getStkName()).append(profitType).append("  "+ownStock.curProfitStr()).append(sfModel.curPrice())
							.append("\n今日: "+sfModel.cur2CloseDisAbsDisStr() +"  "+sfModel.cur2highAbsDisStr()).append("  "+ownStock.highProfitStr());

		notiMyAccount(context,ownStock,"NORMAL",sbTitle);
	}

	public static void showMyAccontMode(Context context,MyAccountStocks ownStock,String offsetType) {
		// TODO 止损止盈
		if (ownStock.getStkQty() == 0){
			return ;
		}

		StringBuffer sbTitle = new StringBuffer("");
		
		String tips = "";
		String profitType = "";
		if (TradeSetUtils.LOSE_OFFSET.equals(offsetType)) {
			tips = "止损";
		}else if (TradeSetUtils.WIN_OFFSET.equals(offsetType)) {
			tips = "止盈";
		}
		
		if (ownStock.getProfitRate() > 0) {
			profitType = "上涨";
		}else {
			profitType = "下跌";
		}
		
		String owner = "默认";
		if (ownStock.getClass().equals(MyAccountStocks.class)) {
			owner = "真实帐号";
		}else if (ownStock.getClass().equals(AIAccountsModel.class)) {
			owner = "模拟帐号";
		}
		
		String rateStr= CaculateUtils.getPercentByFloat(ownStock.getProfitRate());
		if (TradeSetUtils.LOSE_OFFSET.equals(offsetType) || TradeSetUtils.WIN_OFFSET.equals(offsetType)) {
			sbTitle.append(owner).append("持有"+ownStock.getStkName()).append(profitType).append(rateStr).append(",").append("已经达到"+tips).append("条件");
		}else if ("NORMAL".equals(offsetType)) {
			sbTitle.append(owner).append("持有"+ownStock.getStkName()).append(profitType).append(rateStr).append("");
		}else if ("INTIME".equals(offsetType)) {
			sbTitle.append(owner).append("持有"+ownStock.getStkName()).append(profitType).append(rateStr).append("").append("已经达到预设卖出条件").append("条件");;
		}

		notiMyAccount(context, ownStock, offsetType, sbTitle);
	}

	private static void notiMyAccount(Context context, MyAccountStocks ownStock, String offsetType, StringBuffer sbTitle) {
		Notification noti = new Notification(R.drawable.ic_ai, null, System.currentTimeMillis());
		RemoteViews remView = new RemoteViews(context.getPackageName(), R.layout.layout_noti_simple);
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm ss");
		String updateTime = sdf.format(new Date());
		remView.setTextViewText(R.id.tv_noti_title, sbTitle.toString());
		remView.setTextViewText(R.id.tv_noti_content, "更新:"+updateTime);
		noti.contentView = remView;
		Intent intent = new Intent(context, PopTradeDialog.class);
		//配置intent
		IntentUtils.configWithOwnstock(intent, ownStock, OperateModel.TradeType_SELL);

		PendingIntent pIntent = PendingIntent.getActivity(context, IntentContants.REQUEST_START_STARTACTIVITY, intent,PendingIntent.FLAG_UPDATE_CURRENT);
		noti.contentIntent = pIntent;
		noti.defaults = Notification.DEFAULT_ALL;
		noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;

		NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notiManager.notify(NotiIdGenerator.generate(ownStock.getStkCode(), offsetType), noti);

		if (TradeSetUtils.LOSE_OFFSET.equals(offsetType) || TradeSetUtils.WIN_OFFSET.equals(offsetType)){
			FundApplication.getInstance().playSoundPool(NotiIdGenerator.GenerFrom.MYSTOCK_STOP);
		}else if ("INTIME".equals(offsetType)){
			FundApplication.getInstance().playSoundPool(NotiIdGenerator.GenerFrom.MYSTOCK_PRESET);
		}

		if ("Y".equals(ownStock.isRecord)) {
			FundApplication.getInstance().speak(sbTitle.toString());
		}
	}

	public static void playSound(Context mContext, int voiceRaw) {
		String uri = "android.resource://" + mContext.getPackageName() + "/" + voiceRaw;
		Uri no = Uri.parse(uri);
		Ringtone r = RingtoneManager.getRingtone(FundApplication.getInstance(),no);
		r.play();
	}

	public static void playSound(Context mContext, NotiIdGenerator.GenerFrom from){
		int ringRaw = NotiIdGenerator.getNotiRingRaw(from);
		if (ringRaw != -1){
			playSound(mContext, ringRaw);
		}
	}
	
	/**
	 * 移除通知上面的id
	 * @param mContext
	 * @param notiId
	 */
	public static void cancelNoti(Context mContext,int notiId){
		NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
		manager.cancel(notiId);
	}
	
}
